<template>
	<div>
		<!-- 面包屑导航区域 -->
	  <el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
		<el-breadcrumb-item>用户列表</el-breadcrumb-item>
	  </el-breadcrumb>
		<!-- 卡片视图区域 -->
      <el-card>
		<el-row :gutter="20">
			<el-col :span="8">
				<!-- 搜索与添加区域 -->
				<el-input placeholder="请输入账号" v-model="queryInfo.mobile_phone_number" clearable @clear="getUserList">
					<el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
				</el-input>
			</el-col>
			<el-col :span="4">
				<el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
			</el-col>
		</el-row>
	  
	  <!-- 用户列表区域 -->
	  <el-table :data="userlist" border stripe>
		  <el-table-column type="index" ></el-table-column>
		  <el-table-column label="账号" prop="mobile_phone_number"></el-table-column>
		  <el-table-column label="昵称" prop="p_name"></el-table-column>
		  <el-table-column label="性别" prop="p_sex"></el-table-column>
		  <el-table-column label="密码" prop="password"></el-table-column>  
		  <el-table-column label="实名认证" prop="id_card_id"></el-table-column>
		  <el-table-column label="状态">
			  <template slot-scope="scope">
				  <el-switch v-model="scope.row.situation" @change="userStateChanged(scope.row)"></el-switch>
			  </template> 
		  </el-table-column>
		  <el-table-column label="操作" width="120px">
			  <template slot-scope="scope">
				  <el-tooltip effect="dark" content="修改密码" placement="top" :enterable="false">
				     <!-- 修改按钮 -->
				     <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.mobile_phone_number,scope.row.pid,scope.row.password)">
					 </el-button>
				  </el-tooltip>
				  
				  <el-tooltip effect="dark" content="删除用户" placement="top" :enterable="false">
				     <!--  删除按钮 --> 
					 <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.pid)"></el-button>
				  </el-tooltip>
			  </template>
		  </el-table-column>
	  </el-table>
	  <!-- 分页区域 -->
		<el-pagination
	        @size-change="handleSizeChange"
	        @current-change="handleCurrentChange"
	        :current-page="queryInfo.pageNum"
	        :page-sizes="[1, 2, 5, 10]"
	        :page-size="queryInfo.pageSize"
	        layout="total, sizes, prev, pager, next, jumper"
	        :total="total">
		</el-pagination>
	  </el-card>
	  
	  <!-- 添加用户的对话框 -->
	<el-dialog title="提示" :visible.sync="addDialogVisible"
	    width="40%" @close="addDialogClosed">
		<!-- 内容主体区域 -->
	    <el-form :model="addForm" :rules="addFormRules" 
		ref="addFormRef" label-width="80px">
	      <el-form-item label="用户账号" prop="mobile_phone_number">
	        <el-input v-model="addForm.mobile_phone_number"></el-input>
	      </el-form-item>
		  <el-form-item label="密码" prop="password">
		    <el-input v-model="addForm.password"></el-input>
		  </el-form-item>
		  <el-form-item label="昵称" prop="p_name">
		    <el-input v-model="addForm.p_name"></el-input>
		  </el-form-item>
		  <el-form-item label="性别" prop="p_sex">
		    <el-input v-model="addForm.p_sex"></el-input>
		  </el-form-item>
		</el-form>
		<!-- 底部区域 -->
	    <span slot="footer" class="dialog-footer">
	      <el-button @click="addDialogVisible = false">取 消</el-button>
	      <el-button type="primary" @click="addUser">确 定</el-button>
	    </span>
	</el-dialog>
	<!-- 修改用户密码的对话框 -->
	<el-dialog title="提示" :visible.sync="editDialogVisible"
	  width="30%" @close="editDialogClosed">
	  <el-form ref="editFormRef" :rules="editFormRules" :model="editForm" label-width="80px">
	    <el-form-item label="用户账号">
	      <el-input v-model="editForm.mobile_phone_number" disabled></el-input>
	    </el-form-item>
		<el-form-item label="用户密码" prop="password">
		  <el-input v-model="editForm.password" ></el-input>
		</el-form-item>
	  </el-form>
	  <span slot="footer" class="dialog-footer">
	    <el-button @click="editDialogVisible = false">取 消</el-button>
	    <el-button type="primary" @click="editUserInfo">确 定</el-button>
	  </span>
	</el-dialog>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				//获取用户列表的参数对象
				queryInfo: {
					mobile_phone_number: '',
					pageNum: 1,
					pageSize: 2
				},
				userlist: [],
				total: 0,
				// 控制添加用户对话框的显示与隐藏
				addDialogVisible: false,
				// 添加用户的表单数据
				addForm: {
					mobile_phone_number: '',
					password: '',
					p_name: '',
					p_sex: ''
				},
				// 添加表单的验证规则对象
				addFormRules: {
					mobile_phone_number: [
						{ required: true, message: '请输入用户账号', trigger: 'blur' },
						{ min: 11, max: 11, message: '账户长度需11个字符', trigger: 'blur' },
						{ validator: isNum, trigger: 'blur' }
					],
					password: [
						{ required: true, message: '请输入密码', trigger: 'blur' },
						{ min: 3, max: 16, message: '密码长度需在3~16个字符', trigger: 'blur' }
					],
					p_name: [
						{ required: true, message: '请输入昵称', trigger: 'blur' }
					],
					p_sex: [
						{ required: true, message: '请输入性别', trigger: 'blur' },
						{ validator: isSex, trigger: 'blur' }
					]
				},
				// 控制修改用户密码对话框的显示与隐藏
				editDialogVisible: false,
				// 用户账号密码信息对象
				editForm: {
					mobile_phone_number: '',
					pid: '',
					password: ''
				},
				// 修改密码表单的验证规则对象
				editFormRules: {
					password: [
						{ required: true, message: '请输入密码', trigger: 'blur' },
						{ min: 3, max: 16, message: '密码长度需在3~16个字符', trigger: 'blur' }
					]
				}
			}
		},
		created() {
			this.getUserList()
		},
		methods: {
			async getUserList() {
				const { data: res } = await this.$http.get('admin/searchPlayer',{
					params: this.queryInfo
				})
				if(res.code !== 200) {
					return this.$message.error('获取用户列表失败!')
				}
				this.userlist = res.data.list
				this.total = res.data.total
				// 判断用户是否已实名
				for(var i = 0;i<this.userlist.length;i++){
					if(this.userlist[i].id_card_id == null){
						this.userlist[i].id_card_id = '未实名'
					}else{
						this.userlist[i].id_card_id = '已实名'
					}
				}
				// 将situation数值进行转换为ture/false 以便el-swich初始化
				for(var i = 0;i<this.userlist.length;i++){
					if(this.userlist[i].situation == 1){
						this.userlist[i].situation = true
					}else{
						this.userlist[i].situation = false
					}
				}
			},
			// 监听 pagesize 改变的事件
			handleSizeChange(newSize) {
				this.queryInfo.pageSize = newSize
				this.getUserList()
			},
			// 监听 页码值 改变的事件
			handleCurrentChange(newPage) {
				this.queryInfo.pageNum = newPage
				this.getUserList()
			},
			//监听 switch 开关状态
			async userStateChanged(userinfo) {
				var situation;
				if(userinfo.situation == false){
					situation = 0
				}else{
					situation = 1
				}
			
				let data = {"pid":userinfo.pid,"situation":situation};
				const { data: res } = await this.$http.post("admin/updateState",this.$qs.stringify(data));
				if(res.code !== 200) {
					userinfo.situation = !userinfo.situation
					return this.$message.error('更新用户状态失败！')
				}
				this.$message.success('更新用户状态成功！')
			},
			// 监听添加用户对话框关闭事件
			addDialogClosed() {
				this.$refs.addFormRef.resetFields()
			},
			// 点击确定按钮，添加新用户
			addUser() {
				this.$refs.addFormRef.validate(async valid => {
					if(!valid) return
					// 可以发起添加用户的网络请求
					const { data: res } = await this.$http.post("admin/addUser",this.$qs.stringify(this.addForm));
					if(res.code !== 200) {
						userinfo.situation = !userinfo.situation
						return this.$message.error('添加用户失败！')
					}
					this.$message.success('添加用户成功！')
					// 隐藏对话框
					this.addDialogVisible = false;
					// 重新获取用户列表数据
					this.getUserList()
				})
			},
			// 展示修改用户密码的对话框
			async showEditDialog(mobile_phone_number,pid,password) {
				this.editForm.mobile_phone_number = mobile_phone_number
				this.editForm.pid = pid
				this.editForm.password = password
				this.editDialogVisible = true
			},
			// 监听修改用户密码对话框的关闭事件
			editDialogClosed() {
				this.$refs.editFormRef.resetFields()
			},
			//修改用户密码并提交
			editUserInfo() {
				this.$refs.editFormRef.validate(async valid => {
					if(!valid) return 
					//发起修改用户密码的数据请求
					let data = {"pid":this.editForm.pid,"password":this.editForm.password};
					const { data: res } = await this.$http.post("updatepassword",this.$qs.stringify(data));
					this.$message.success('修改成功！')
					// 隐藏对话框
					this.editDialogVisible = false;
					// 重新获取用户列表数据
					this.getUserList()
				})
			},
			// 根据id删除对于的用户信息
			async removeUserById(pid) {
				// 弹框询问用户是否删除用户
				const confrimResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
				          confirmButtonText: '确定',
				          cancelButtonText: '取消',
				          type: 'warning'
				        }).catch(err => err)
				
				//如果用户确认删除，则返回值为字符串confrim
				//如果用户取消了删除，则返回值为字符串cancel
				// console.log(confrimResult)
				if(confrimResult !== 'confirm') {
					return this.$message.info('已取消删除')
				}
				let data = {"pid":pid};
				const { data: res } = await this.$http.post("admin/deleteUser",this.$qs.stringify(data));
				if(res.code !== 200) {
					return this.$message.error('删除用户失败！')
				}
				this.$message.success('删除用户成功！')
				this.getUserList()
			}
			
		}
	}
	
	//自定义校验规则
	// 用户账号数字判断
	 const isNum = (rule, value, callback) => {
	      const username= /^[0-9]*$/
	      if (!username.test(value)) {
	        callback(new Error('只能为数字'))
	      }else{
	        callback()
	      }
	    }
	// 用户性别判断
	const isSex = (rule, value, callback) => {
	     const username= /^男$|^女$/
	     if (!username.test(value)) {
	       callback(new Error('只能为男或女'))
	     }else{
	       callback()
	     }
	   }
</script>

<style lang="less" scoped>
</style>
